package com.bsierp.util.tags;

import java.util.List;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

import com.bsierp.business.pojo.User;
import com.bsierp.util.Constants;
import com.bsierp.util.hibernate.HibernateSessionFactory;

public class DisplayAutoComplete extends TagSupport {
	
	 String keyWord;
	
	
public String getKeyWord() {
		return keyWord;
	}

	public void setKeyWord(String keyWord) {
		this.keyWord = keyWord;
	}

private Log log = LogFactory.getLog(this.getClass().getName());

public int doEndTag( ) throws JspException
{
	
 JspWriter out = pageContext.getOut();
 
 String hql="select p.id.product.productModel,count(p.id.product.productModel) from PrivateProduct p where p.id.user=:user and( p.id.product.productModel like:productModel or p.id.product.productName like:productName) group by p.id.product.productModel" ;
	
try{
	HttpSession ses = pageContext.getSession();


	User u=null;
	if(ses.getAttribute(Constants.userLogin_sessionindex)!=null){
		u=(User)ses.getAttribute(Constants.userLogin_sessionindex);
	}
	
	
	SessionFactory sessionFactory= HibernateSessionFactory.getSessionFactory();
	Session session=sessionFactory.openSession();
	Transaction tx=null;
	String option_str="";
		try {
		tx=session.beginTransaction();
		Query q=session.createQuery(hql);
		 q.setEntity("user", u);
		    q.setString("productName", keyWord+"%");
		    q.setString("productModel",keyWord+"%");
		   
		
		List l=q.list();
		StringBuffer sb=new StringBuffer();
    		
		  for(int i=0;i<l.size();i++){
	            Object[] ob=(Object[])l.get(i);
	            sb.append(ob[0]+"|"+ob[0]+"---"+ob[1]+"\n");   //   键|键值   格式是提供给autocomplete插件用的
	 	         
	            }
		
		
		out.print(sb.toString());
	
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			session.close();
		}
		
		


	
}catch (Exception ex)
 {
   throw new JspTagException("IOException:" + ex.toString());
 }
 return super.doEndTag();
}
}

